package com.loveyukari.service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.google.gson.JsonObject;
import com.loveyukari.model.Room;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.loveyukari.dao.RegisterDao;
import com.loveyukari.model.Auth;
import com.loveyukari.model.AuthRegister;
import com.loveyukari.model.Register;

import net.sf.json.JSONObject;

/**
 *
 * yangshaohua 2017年4月17日下午4:56:50
 **/
@Service
public class NewRegisterService {

	@Autowired
	private AuthService authService;

	@Autowired
	private RegisterDao registerDao;

	@Autowired
	private AuthScoreService authScoreService;

	@Autowired
	private RedisService redisService;

	@Autowired
	private PermissionService permissionService;

	@Autowired
	private RoomService roomService;



	private Logger logger = LoggerFactory.getLogger(NewRegisterService.class);
	private static final String REGISTER_AUTH_KEY = "register:auth:";
	private static final String REGISTER_KEY = "register";



	public List<JSONObject> getAuthRegisterList(int authId){
		//权限验证
		List<Register> registerList = registerDao.selectAll();
		List<AuthRegister> list = registerDao.selectAuthRegisterList(authId);
		ArrayList<JSONObject> result = new ArrayList<>();
		if (list.isEmpty()){
			return result;
		}
		HashMap<Integer, AuthRegister> map = new HashMap<>();
		for (AuthRegister authRegister :
				list) {
			map.put(authRegister.getRegisterId(),authRegister);
		}
		for (Register register :
				registerList) {
			AuthRegister authRegister = map.get(register.getId());
			if (result.isEmpty()){
				if (authRegister != null){
					JSONObject json = createAuthRegisterJson(register, authRegister);
					result.add(json);
				}
			} else {
				JSONObject json = createAuthRegisterJson(register, authRegister);
				result.add(json);
			}
		}
		return result;
	}
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	private JSONObject createAuthRegisterJson(Register register,AuthRegister authRegister){
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("registerTime", sdf.format(register.getStartTime()));
		if (authRegister == null){
			jsonObject.put("status",-1);
		} else {
			jsonObject.put("status",authRegister.getStatus());
		}
		return jsonObject;
	}

	//获取所有签到用户
	public List<Auth> getRegisterAuthList(){
		List<Integer> authIdList = permissionService.getAuthIdByPermission(1);
		ArrayList<Auth> list = new ArrayList<>();
		for (Integer authId:authIdList
			 ) {
			Auth auth = authService.getCacheAuth(authId);
			if (auth != null){
				list.add(auth);
			}
		}
		return list;
	}
	
	//获取用户签到信息
	public List<JSONObject> getAuthRegisterInfo(int[] authIds){
		List<JSONObject> result = new ArrayList<JSONObject>();
		for (Integer authId : authIds) {
			if (authId == null){
				continue;
			}
			String key = REGISTER_AUTH_KEY+authId;
			AuthRegister authRegister = redisService.get(key,AuthRegister.class);
			if (authRegister != null && authRegister.getCreateTime() != null){
				JSONObject jsonObject = new JSONObject();
				JSONObject talk = authService.getAuthTalk(authId).get(0);
				jsonObject.putAll(talk);
				jsonObject.put("authId", authId);
				jsonObject.put("status", authRegister.getStatus());
				jsonObject.put("createTime", authRegister.getCreateTime());
				result.add(jsonObject);
			}
		}
		return result;
	}

	public Register getRegister(int id){
		Register register = registerDao.selectById(id);
		return register;
	}

	//获取签到日期信息
	private Register getCacheRegister(){
		Register register = redisService.get(REGISTER_KEY,Register.class);
		if (register == null){
			register = this.registerDao.selectByLast();
			if (register != null){
				redisService.set(REGISTER_KEY, register,30,TimeUnit.MINUTES);
			}
		}
		return register;
	}
	
	//获取用户签到信息列表
	public JSONObject getAuthRegisterList(int[] authIds,int start,int size){
		JSONObject result = new JSONObject();
		List<Register> registerList = registerDao.selectRegisterList(start, size);
		result.put("registerList", registerList);
		List<JSONObject> authRegisterList = new ArrayList<JSONObject>();
		for (Integer authId : authIds) {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("authId", authId);
			List<Integer> statusList = new ArrayList<Integer>();
			for (Register register : registerList) {
				AuthRegister authRegister = registerDao.selectAuthRegister(register.getId(), authId);
				if(authRegister == null){
					statusList.add(-1);
				} else {
					statusList.add(authRegister.getStatus());
				}
			}
			jsonObject.put("statusList", statusList);
			authRegisterList.add(jsonObject);
		}
		result.put("authRegisterList", authRegisterList);
		return result;
	}

	public void setRegisterAuthTalk(int authId) {
		if (this.getCacheRegister() != null) {
			String key = REGISTER_AUTH_KEY + authId;
			AuthRegister authRegister = redisService.get(key,AuthRegister.class);
			if (authRegister == null) {
				return;
			} else {
				if (authRegister.getCreateTime() == null){
					//签到
					authRegister = this.registerAuth(authId);
				}
			}
		}
	}
	
	public AuthRegister registerAuth(int authId){
		Register register = this.getCacheRegister();
		if (register == null){
			return null;
		} else {
			int status = 0;
			if (System.currentTimeMillis() - register.getStartTime().getTime() > 1800000){
				status = 1;
			}
			registerAuth(authId, status);
			return registerDao.selectAuthRegister(register.getId(), authId);
		}
	}


	public void registerAuth(int authId, int status) {
		logger.info("register "+authId+" status: "+status);
		Register register = this.getCacheRegister();
		AuthRegister authRegister = registerDao.selectAuthRegister(register.getId(), authId);
		if (authRegister == null){
			registerDao.insertAuthRegister(authId, register.getId(), status);
			switch (status){
				case 0:authScoreService.addAuthScore(authId,3);break;
				case 1:authScoreService.addAuthScore(authId,1);break;
			}
		} else {
			registerDao.updateAuthRegister(register.getId(), authId, status);
		}
		String key = REGISTER_AUTH_KEY + authId;
		authRegister = registerDao.selectAuthRegister(register.getId(), authId);
		redisService.set(key, authRegister);
		
	}
	
	public Register startRegister(){
		logger.info("start register "+System.currentTimeMillis());
		Register register = registerDao.selectByLast();
		if (register == null){
			registerDao.startRegister();
		}
		List<Integer> authIdlist = permissionService.getAuthIdByPermission(1);
		register = this.registerDao.selectByLast();

		redisService.del(REGISTER_KEY);
		redisService.set(REGISTER_KEY, register,30,TimeUnit.MINUTES);
		//初始化用户缓存
		Set<String> keys = redisService.keys(REGISTER_AUTH_KEY + "*");
		redisService.del(keys);
		for (Integer authId : authIdlist) {
			String key = REGISTER_AUTH_KEY + authId;
			AuthRegister authRegister = registerDao.selectAuthRegister(register.getId(), authId);
			if (authRegister == null){
				authRegister = new AuthRegister();
				authRegister.setAuthId(authId);
				authRegister.setRegisterId(register.getId());
				redisService.set(key, authRegister);
			} else {
				redisService.set(key, authRegister);
			}
		}
		return this.getCacheRegister();
	}
	
	public void stopRegister(){
		registerDao.stopRegister();
	}
	
	//开播自动签到
	public void liveStartRegister(){
		Date now = new Date();
		Date today = DateUtils.truncate(now, Calendar.DAY_OF_MONTH);
		Date start = DateUtils.addHours(today, 6);
		Register register = registerDao.selectByLast();
		if (register != null){
			if (now.getTime() > start.getTime()){
				if (register.getStartTime().getTime() < start.getTime()){
					this.stopRegister();
				}
			} else {
				if (register.getStartTime().getTime() < DateUtils.addHours(start, -24).getTime()){
					this.stopRegister();
				}
			}
		}
		this.startRegister();
	}


}
